package AppleCakeMining;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import util.FileHandler;

public class SolutionMerger {
	//indicates if partialfile should go first and be filled with second one (true)
	//or full one should go first and the last elements be replaced with partial one
	private static boolean partialFirst = true; 
	private static int length = 500;
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String partialFile = "lift.txt";
		String fullFile = "NN-500songs.txt";
		String outputFile = "Merged"+partialFile+fullFile;
		if(!partialFirst) {
			outputFile = "Merged"+fullFile+partialFile;
		}
		
		FileReader fr;
		FileReader fr2;
		FileHandler fh = FileHandler.getInstance();
		fh.deleteFile(outputFile);
		try {
			fr = new FileReader(partialFile);
			fr2 = new FileReader(fullFile);
			BufferedReader in = new BufferedReader(fr);
			BufferedReader in2 = new BufferedReader(fr2);
			while (true) {
				try {
					String read = in.readLine();
					String read2 = in2.readLine();
					if (read2 == null)	break;
					if (read == null) {
						read = "";
					}
					String merged = merge(read, read2);
					fh.write(merged, outputFile);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	private static String merge(String read, String read2) {
		if(read.equals("")) {
			return read2 +"\n";
		}
		String[] split = read.split(" ");
		String[] split2 = read2.split(" ");
		
		if(partialFirst) {
			int size = split.length;
			for(int i = 0; size < length; ++i) {
				boolean found = false;
				for(int j = 0; j < split.length && !found; ++j) {
	//				System.out.println(i + " " + j + " " + size);
					if(split2[i].equals(split[j]))
						found = true;
				}
				if(!found) {
					read += " " + split2[i];
					++size;
				}
			}
		}
		else {
			ArrayList<String> toAdd = new ArrayList<String>();
			for(int i = 0; i < split.length; ++i) {
				boolean found = false;
				for(int j = 0; j < split2.length && !found; ++j) {
	//				System.out.println(i + " " + j + " " + size);
					if(split[i].equals(split2[j]))
						found = true;
				}
				if(!found) {
					toAdd.add(split[i]);
				}
			}
			read = "";
			for(int i = 0; i < split2.length - toAdd.size(); ++i) {
				read += split2[i] +" ";
			}
			for(String s:toAdd) {
				read += s + " ";
			}
			
		}
		return read +"\n";
	}

}
